const response = require("../../utils/response");
const { handleDatabaseError } = require("../../utils/dberrordeal");
const MenuService = require('../../services/system/menuService');

class MenuController {
    static async addBtnRole(ctx) {
        const { menuId, ...buttonData } = ctx.request.body;
        const res = await MenuService.addButtonRole(menuId, buttonData);
        res ? response.success(ctx, {}) : response.error(ctx, {});
    }

    static async getBtnRole(ctx) {
        const { id } = ctx.request.body;
        const res = await MenuService.getButtonRoles(id);
        res ? response.success(ctx, { data: res }) : response.error(ctx, {});
    }

    static async putBtnRole(ctx) {
        const { data: buttonData, did: buttonId } = ctx.request.body;
        const res = await MenuService.updateButtonRole(buttonData.menuId, buttonId, buttonData);
        res ? response.success(ctx, {}) : response.error(ctx, {});
    }

    static async deleteBtnRole(ctx) {
        const { id: menuId, did: buttonId } = ctx.request.body;
        const res = await MenuService.deleteButtonRole(menuId, buttonId);
        res ? response.success(ctx, {}) : response.error(ctx, {});
    }

    static async addMenu(ctx) {
        const menuData = ctx.request.body;
        await MenuService.createMenu(menuData)
            .then(() => response.success(ctx, {}))
            .catch(err => handleDatabaseError(ctx, err, '路由名称重复'));
    }

    static async putMenu(ctx) {
        const { id, ...menuData } = ctx.request.body;
        const res = await MenuService.updateMenu(id, menuData);
        res ? response.success(ctx, {}) : response.error(ctx, {});
    }

    static async getMenuDetail(ctx) {
        const { id } = ctx.request.body;
        const res = await MenuService.getMenuById(id);
        res ? response.success(ctx, { data: res }) : response.error(ctx, {});
    }

    static async getMenuList(ctx) {
        const res = await MenuService.getMenuList();
        res ? response.success(ctx, { data: res }) : response.error(ctx, {});
    }

    static async deleteMenu(ctx) {
        const { id } = ctx.request.body;
        const res = await MenuService.deleteMenu(id);
        res ? response.success(ctx, {}) : response.error(ctx, {});
    }
}

module.exports = MenuController;
